package training.bms.persistence;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.Order;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.lang.StringUtils;

import training.bms.business.Tag;
import training.bms.business.TagSearchOptions;
import training.bms.business.Tag_;
import training.framework.presentation.AbstractEntityDao;

public class TagDao extends AbstractEntityDao<Integer, Tag, TagSearchOptions> {

	public TagDao() {
		super(EntityManagerFactorySingleton.FACTORY, Tag.class);
	}

	@Override
	protected Order toOrder(CriteriaBuilder builder, Root<Tag> root) {
		return builder.asc(root.get(Tag_.name));
	}

	@Override
	protected Predicate toPredicate(CriteriaBuilder builder, Root<Tag> root,
			TagSearchOptions options) {
		
		Predicate namePredicate;
		String tagName = options.getName();
		if (StringUtils.isBlank(tagName)) {
			namePredicate = builder.conjunction();								
		} else {
			namePredicate = builder.like(
				builder.lower(root.get(Tag_.name)), 
				toLikeParameter(tagName)
			);
		}
		
		Predicate predicate = builder.and(namePredicate);
		return predicate;
	}
	
}
